package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GulimallFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            /**
             *
             * @param template feign 构建的请求对象
             */
            @Override
            public void apply(feign.RequestTemplate template) {
                // Spring 提供了一个 RequestContextHolder，可以获取到当前线程的请求对象，通过这个对象，可以获取到当前请求的 Cookie 等信息
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    // 获取当前请求对象
                    HttpServletRequest request = attributes.getRequest();
                    // 获取当前请求的 Cookie 等信息，并设置到 feign 的请求对象中
                    template.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }
}